export default {
  namespaced: true,

  state: () => ({
    cart: JSON.parse(uni.getStorageSync("cart") || "[]")
  }),

  mutations: {
    // 添加购物车
    addCart(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id);

      if (!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }

      this.commit("m_cart/saveStorage")
    },

    // 保存到本地
    saveStorage(state) {
      uni.setStorageSync("cart", JSON.stringify(state.cart))
    },

    // 更新购物车勾选状态
    updateGoodsState(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id);

      if (findResult) {
        findResult.goods_state = goods.goods_state
      }

      this.commit("m_cart/saveStorage")
    },

    // 更新商品数量
    updateGoodsCount(state, goods) {
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id);

      if (findResult) {
        findResult.goods_count = goods.goods_count
      }

      this.commit("m_cart/saveStorage")
    },

    // 根据 Id 删除对应商品
    removeGoodsById(state, id) {
      state.cart = state.cart.filter(x => x.goods_id !== id)

      this.commit("m_cart/saveStorage")
    },

    // 商品全选状态
    updateAllState(state, newState) {
      state.cart.forEach(x => x.goods_state = newState)

      this.commit("m_cart/saveStorage")
    }
  },

  getters: {
    total(state) {
      // let c = 0;
      // state.cart.forEach(x => c += x.goods_count)
      // return c
      return state.cart.reduce((t, x) => t += x.goods_count, 0)
    },

    // 已勾选商品总数量
    checkoutCount(state) {
      return state.cart.filter(item => item.goods_state).reduce((t, x) => t += x.goods_count, 0)
    },

    // 已勾选商品总价格
    checkAmount(state) {
      return state.cart.filter(x => x.goods_state).reduce((a, x) => a += x.goods_count * x.goods_price, 0).toFixed(2)
    }
  }
}